//
//  CustomCameraController.m
//  OnionHome
//
//  Created by fengjie on 2019/9/30.
//  Copyright © 2019 FengJie. All rights reserved.
//

#import "CustomCameraController.h"

@interface CustomCameraController ()
{
    int count ;
    NSInteger selectedFirstTag;
    NSInteger selectedSecondTag;
}
/**顶部拍照按钮视图*/
@property (nonatomic,strong)UIView*downView;
/**拍照按钮*/
@property (nonatomic,strong)UIButton*photoButotn;
/**拍照后的图片*/
@property (nonatomic,strong)UIImage*photopImage;
@end

@implementation CustomCameraController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES animated:nil];
    [self MakeMyCapture];
    [self turnOffLed];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    if (self.session) {
        [self.session startRunning];
    }
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
    if (self.session) {
        [self.session stopRunning];
    }
}
/// 打开闪光灯
-(void)turnOnLed {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        [device setFlashMode:AVCaptureFlashModeOn];
        [device unlockForConfiguration];
    }
}
/// 关闭闪光灯
-(void)turnOffLed {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        //        [device setTorchMode: AVCaptureTorchModeOff];
        [device setFlashMode:AVCaptureFlashModeOff];
        [device unlockForConfiguration];
    }
}
/// 点击切换闪光灯
/// @param btn <#btn description#>
-(void)rightBarBtnClick:(UIBarButtonItem*)btn{
    DLog(@"---%d",count);
    count++;
    if (count%2==1){
        [self turnOffLed];
        [btn setImage:[UIImage imageNamed:@"camera_flash_off"]];
    }else
    {
        [self turnOnLed];
        [btn setImage:[UIImage imageNamed:@"camera_flash_on"]];
    }
    
    
}
/// 退出
-(void)backBarBtnClick{
    if (self.isPhotos) {
        BlockSafeRun(self.dismissView);
    }else{
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
}
#pragma mark 构造自定义相机
-(void)MakeMyCapture{
    self.session = [[AVCaptureSession alloc] init];
    NSError *error;
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //更改这个设置的时候必须先锁定设备，修改完后再解锁，否则崩溃
    [device lockForConfiguration:nil];
    //设置闪光灯为自动
    [device setFlashMode:AVCaptureFlashModeAuto];
    [device unlockForConfiguration];
    
    self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error];
    if (error) {
        DLog(@"%@",error);
    }
    self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary * outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil];
    [self.stillImageOutput setOutputSettings:outputSettings];
    
    if ([self.session canAddInput:self.videoInput]) {
        [self.session addInput:self.videoInput];
    }
    if ([self.session canAddOutput:self.stillImageOutput]) {
        [self.session addOutput:self.stillImageOutput];
    }
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    
    self.previewLayer.frame = CGRectMake(0,0,KScreenWidth ,KScreenHeight);
    self.previewLayer.videoGravity = AVLayerVideoGravityResize;
    //    [self.previewLayer setBounds:self.view.bounds];
    self.previewLayer.contentsScale = [UIScreen mainScreen].scale;
    self.previewLayer.backgroundColor = [[UIColor blackColor]CGColor];
    self.view.layer.masksToBounds = YES;
    
    [self.view.layer addSublayer:self.previewLayer];
    //创建相机下面自定义视图
    [self createCusphototV];
}
/// 创建相机下面自定义视图
-(void)createCusphototV{
    UIView * navView = [self createNavView];

    [self.view addSubview:navView];
    [self.view addSubview:self.downView];
    
    [navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
    }];

    [self.downView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-70);
        make.centerX.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
    }];
}

/// 点击拍照按钮
/// @param button <#button description#>
-(void)SavePhoto:(UIButton *)button{
    //进行拍照保存图片
    AVCaptureConnection *conntion = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
    if (!conntion) {//AVMediaTypeMetadata  AVMediaTypeVideo
        DLog(@"拍照失败!");
        return;
    }
    kWeakSelf(weakSelf);
    [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:conntion completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer == nil) {
            return ;
        }
        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        
        weakSelf.photopImage = [UIImage imageWithData:imageData];
        
       [self Dophoto];
        
    }];
}

/// 拍照结束，显示照片
-(void)Dophoto{
    UIView *viewb = [[UIView alloc]init];
    viewb.backgroundColor = KWhiteColor;
    
    [self.view addSubview:viewb];
    
    [viewb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.mas_equalTo(0);
    }];
    
    UIImageView *imagev = [[UIImageView alloc] initWithImage:self.photopImage];
//    imagev.contentMode = UIViewContentModeScaleAspectFit;
//    imagev.frame = CGRectMake(0, 30, KScreenWidth, KScreenHeight -100 - 30);
    [viewb addSubview:imagev];
    
    
    UIButton *leftbutton = [[UIButton alloc]init];
//    [leftbutton setTitle:@"重拍" forState:UIControlStateNormal];
    [leftbutton setImage:IMAGE_NAMED(@"取消") forState:UIControlStateNormal];
    [leftbutton setBackgroundColor:UIColorFromRGB(0xF5F7F5)];
    ViewRadius(leftbutton, 45/2);
    leftbutton.tag = 1001;
    [leftbutton setTitleColor:KBlackColor forState:UIControlStateNormal];
    [viewb addSubview:leftbutton];
//    leftbutton.frame = CGRectMake(60, KScreenHeight-50, 45, 45);
    [leftbutton addTarget:self action:@selector(hitopbutton:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *rightbutton = [[UIButton alloc]init];
    [rightbutton setImage:IMAGE_NAMED(@"确定") forState:UIControlStateNormal];
//    [rightbutton setTitle:@"确定" forState:UIControlStateNormal];
    rightbutton.tag = 1000;
    [rightbutton setTitleColor:KBlackColor forState:UIControlStateNormal];
    [viewb addSubview:rightbutton];
//    rightbutton.frame = CGRectMake(KScreenWidth-60 - 45, KScreenHeight-50, 45, 45);
    [rightbutton addTarget:self action:@selector(hitopbutton:) forControlEvents:UIControlEventTouchUpInside];

    [imagev mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-120);
    }];

    [leftbutton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(60);
        make.bottom.mas_equalTo(-70);
        make.width.height.mas_equalTo(45);
    }];
    [rightbutton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-60);
        make.bottom.mas_equalTo(-70);
        make.width.height.mas_equalTo(45);
    }];

}

/// 点击确定结束拍照
/// @param button <#button description#>
-(void)hitopbutton:(UIButton *)button{
    [button.superview removeFromSuperview];
    if(button.tag == 1000){
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        BlockSafeRun(self.rentunBlock,self.photopImage);
    }
}

#pragma mark ---懒加载
-(UIView*)downView{
    if(!_downView){
        _downView=[UIView new];
        _downView.userInteractionEnabled = YES;
        
        UILabel *photoLable = [[UILabel alloc] initWithFrame:CGRectZero];
        photoLable.text = @"轻触拍照";
        photoLable.font = [UIFont systemFontOfSize:11];
        photoLable.textColor = UIColorFromRGB(0x959E97);
        
        [_downView addSubview:photoLable];
        [_downView addSubview:self.photoButotn];
        [photoLable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(0);
            make.top.mas_equalTo(0);
        }];
        
        [self.photoButotn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(0);
            make.width.height.mas_equalTo(72);
            make.top.mas_equalTo(photoLable.mas_bottom).offset(8);
            make.bottom.mas_equalTo(0);
        }];

        
    }
    return _downView;
}
-(UIButton*)photoButotn{
    if(!_photoButotn){
        _photoButotn=[UIButton new];
        [_photoButotn setBackgroundImage:IMAGE_NAMED(@"拍照") forState:UIControlStateNormal];
        [_photoButotn addTarget:self action:@selector(SavePhoto:) forControlEvents:UIControlEventTouchUpInside];
        ViewBorderRadius(_photoButotn, 36, 4, RGBA(0, 153, 102, 0.28));
    }
    return _photoButotn;
}
-(void)shanguandengAction:(UIButton *)button{
    button.selected = !button.selected;

}
/// 导航栏视图
-(UIView *)createNavView{
    UIView * view = UIView.new;
    
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"取消" forState:UIControlStateNormal];
    backBtn.titleLabel.font = SYSTEMFONT(16);
    [backBtn setTitleColor:UIColorFromRGB(0x273323) forState:UIControlStateNormal];
    kWeakSelf(weakSelf);
    [backBtn addActionHandler:^{
        [weakSelf backBarBtnClick];
    }];
    
    UIButton * rightBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
//    [rightBtn1 setTitle:@"闪光灯" forState:UIControlStateNormal];
    [rightBtn1 setImage:IMAGE_NAMED(@"icon_flash_on_24x24") forState:UIControlStateNormal];
    [rightBtn1 setImage:IMAGE_NAMED(@"icon_flash_open") forState:UIControlStateSelected];

    rightBtn1.titleLabel.font = SYSTEMFONT(16);
    [rightBtn1 setTitleColor:UIColorFromRGB(0x273323) forState:UIControlStateNormal];
    [rightBtn1 addTarget:self action:@selector(shanguandengAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * rightBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn2 setImage:IMAGE_NAMED(@"取消") forState:UIControlStateNormal];
//    [rightBtn2 setTitle:@"切换前后摄像头" forState:UIControlStateNormal];
    rightBtn2.titleLabel.font = SYSTEMFONT(16);
    [rightBtn2 setTitleColor:UIColorFromRGB(0x273323) forState:UIControlStateNormal];
    
    [rightBtn2 addActionHandler:^{
        [weakSelf changeButtonAction];
    }];
    
    [view addSubview:backBtn];
    [view addSubview:rightBtn1];
    [view addSubview:rightBtn2];

    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(16);
        make.bottom.mas_equalTo(-16);
    }];
    [rightBtn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-16);
        make.centerY.mas_equalTo(0);
    }];
    [rightBtn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(rightBtn2.mas_left).offset(-20);
        make.centerY.mas_equalTo(0);
    }];

    return view;
}
/**
 切换摄像头按钮的点击方法的实现（切换摄像头时可以添加转场动画）
 */
-(void)changeButtonAction{
    //获取摄像头的数量（该方法会返回当前能够输入视频的全部设备，包括前后摄像头和外接设备）
    NSInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
    //摄像头的数量小于等于1的时候直接返回
    if (cameraCount <= 1) {
        return;
    }
    AVCaptureDevice *newCamera = nil;
    AVCaptureDeviceInput *newInput = nil;
    //获取当前相机的方向（前/后）
    AVCaptureDevicePosition position = [[self.videoInput device] position];

    //为摄像头的转换加转场动画
    CATransition *animation = [CATransition animation];
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.duration = 0.5;
    animation.type = @"oglFlip";

    if (position == AVCaptureDevicePositionFront) {
        newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
        animation.subtype = kCATransitionFromLeft;

    }else if (position == AVCaptureDevicePositionBack){
        newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
        animation.subtype = kCATransitionFromRight;
    }
    [self.previewLayer addAnimation:animation forKey:nil];

    //输入流
    newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
    if (newInput != nil) {
        [self.session beginConfiguration];
        //先移除原来的input
        [self.session removeInput:self.videoInput];
        if ([self.session canAddInput:newInput]) {
            [self.session addInput:newInput];
            self.videoInput = newInput;
        }else{
            //如果不能加现在的input，就加原来的input
            [self.session addInput:self.videoInput];
        }
        [self.session commitConfiguration];
    }

}

-(AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices )
        if ( device.position == position )
            return device;
    return nil;
}
@end
